package okhttp3.internal.connection;

import java.io.IOException;
import java.lang.ref.Reference;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import o.ftt;
import o.fty;
import o.ftz;
import o.fud;
import o.fuf;
import o.fuh;
import o.fuk;
import o.fum;
import o.fuo;
import o.fur;
import o.fus;
import o.fut;
import o.fuv;
import o.fux;
import o.fvb;
import o.fvb.d;
import o.fvc;
import o.fvg;
import o.fvi;
import o.fvm.b;
import o.fvo;
import o.fvr;
import o.fvv;
import o.fwe;
import o.fwf;
import o.fwh;
import o.fwj;
import o.fwk;
import o.fwk.a;
import o.fwy;
import o.fxa.e;
import o.fxc;
import o.fxg;
import o.fxj;
import o.fxr;
import o.fxw;
import okhttp3.Route;

public final class RealConnection extends a implements fuh {
    public static final long MAX_RESERVE_DURATION_NS = 1000000000;
    private static final int MAX_SERVER_PROCESS_TIME = 1000;
    private static final int MAX_TUNNEL_ATTEMPTS = 21;
    private static final String NPE_THROW_WITH_NULL = "throw with null exception";
    private static final int RTT_FACTOR = 4;
    public int allocationLimit = 1;
    public final List<Reference<StreamAllocation>> allocations = new ArrayList();
    private fvi concurrentConnect = null;
    private Route connectedRoute = null;
    private final fuf connectionPool;
    int consecutiveTimeoutCount = 0;
    int consecutiveTimeoutThreshold = 0;
    private fuk handshake;
    private fwk http2Connection;
    public long idleAtNanos = Long.MAX_VALUE;
    public long keepaliveTimestampNs = 0;
    public boolean noNewStreams;
    private fut protocol;
    private Socket rawSocket;
    long roughRtt = 0;
    private Route route;
    private b routeSelection = null;
    private fxj sink;
    private Socket socket;
    private fxg source;
    public int successCount;

    public RealConnection(fuf o_fuf, Route route) {
        this.connectionPool = o_fuf;
        this.route = route;
    }

    public static RealConnection testConnection(fuf o_fuf, Route route, Socket socket, long j) {
        RealConnection realConnection = new RealConnection(o_fuf, route);
        realConnection.socket = socket;
        realConnection.idleAtNanos = j;
        return realConnection;
    }

    public void prepareConcurrentConnect(ArrayList<InetSocketAddress> arrayList, int i) {
        if (arrayList != null) {
            this.concurrentConnect = new fvi(arrayList, i);
        }
    }

    public void setRouteSelection(b bVar) {
        this.routeSelection = bVar;
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public void connect(int r9, int r10, int r11, int r12, boolean r13, o.ftz r14, o.fum r15) {
        /*
        r8 = this;
        r0 = r8.protocol;
        if (r0 == 0) goto L_0x000c;
    L_0x0004:
        r0 = new java.lang.IllegalStateException;
        r1 = "already connected";
        r0.<init>(r1);
        throw r0;
    L_0x000c:
        r0 = 0;
        r1 = r8.route;
        r1 = r1.address();
        r1 = r1.ʼ();
        r7 = new o.fvo;
        r7.<init>(r1);
        r2 = r8.route;
        r2 = r2.address();
        r2 = r2.ॱॱ();
        if (r2 != 0) goto L_0x00a8;
    L_0x0028:
        r2 = o.fud.ˎ;
        r1 = r1.contains(r2);
        if (r1 != 0) goto L_0x003d;
    L_0x0030:
        r0 = new okhttp3.internal.connection.RouteException;
        r1 = new java.net.UnknownServiceException;
        r2 = "CLEARTEXT communication not enabled for client";
        r1.<init>(r2);
        r0.<init>(r1);
        throw r0;
    L_0x003d:
        r1 = r8.route;
        r1 = r1.address();
        r1 = r1.ˊ();
        r1 = r1.ʻ();
        r2 = o.fwy.ˋ();
        r2 = r2.ˊ(r1);
        if (r2 != 0) goto L_0x0079;
    L_0x0055:
        r0 = new okhttp3.internal.connection.RouteException;
        r2 = new java.net.UnknownServiceException;
        r3 = new java.lang.StringBuilder;
        r3.<init>();
        r4 = "CLEARTEXT communication to ";
        r3 = r3.append(r4);
        r1 = r3.append(r1);
        r3 = " not permitted by network security policy";
        r1 = r1.append(r3);
        r1 = r1.toString();
        r2.<init>(r1);
        r0.<init>(r2);
        throw r0;
    L_0x0079:
        r6 = r0;
    L_0x007a:
        r0 = r8.route;	 Catch:{ IOException -> 0x00df }
        r0 = r0.requiresTunnel();	 Catch:{ IOException -> 0x00df }
        if (r0 == 0) goto L_0x00c7;
    L_0x0082:
        r0 = r8;
        r1 = r9;
        r2 = r10;
        r3 = r11;
        r4 = r14;
        r5 = r15;
        r0.connectTunnel(r1, r2, r3, r4, r5);	 Catch:{ IOException -> 0x00df }
        r0 = r8.rawSocket;	 Catch:{ IOException -> 0x00df }
        if (r0 != 0) goto L_0x00ca;
    L_0x008f:
        r0 = r8.route;
        r0 = r0.requiresTunnel();
        if (r0 == 0) goto L_0x0129;
    L_0x0097:
        r0 = r8.rawSocket;
        if (r0 != 0) goto L_0x0129;
    L_0x009b:
        r0 = new java.net.ProtocolException;
        r1 = "Too many tunnel connections attempted: 21";
        r0.<init>(r1);
        r1 = new okhttp3.internal.connection.RouteException;
        r1.<init>(r0);
        throw r1;
    L_0x00a8:
        r1 = r8.route;
        r1 = r1.address();
        r1 = r1.ʻ();
        r2 = o.fut.H2_PRIOR_KNOWLEDGE;
        r1 = r1.contains(r2);
        if (r1 == 0) goto L_0x013d;
    L_0x00ba:
        r0 = new okhttp3.internal.connection.RouteException;
        r1 = new java.net.UnknownServiceException;
        r2 = "H2_PRIOR_KNOWLEDGE cannot be used with HTTPS";
        r1.<init>(r2);
        r0.<init>(r1);
        throw r0;
    L_0x00c7:
        r8.connectSocket(r9, r10, r14, r15);	 Catch:{ IOException -> 0x00df }
    L_0x00ca:
        r8.establishProtocol(r7, r12, r14, r15);	 Catch:{ IOException -> 0x00df }
        r0 = r8.route;	 Catch:{ IOException -> 0x00df }
        r0 = r0.socketAddress();	 Catch:{ IOException -> 0x00df }
        r1 = r8.route;	 Catch:{ IOException -> 0x00df }
        r1 = r1.proxy();	 Catch:{ IOException -> 0x00df }
        r2 = r8.protocol;	 Catch:{ IOException -> 0x00df }
        r15.connectEnd(r14, r0, r1, r2);	 Catch:{ IOException -> 0x00df }
        goto L_0x008f;
    L_0x00df:
        r5 = move-exception;
        r0 = r8.socket;
        o.fvg.ˎ(r0);
        r0 = r8.rawSocket;
        o.fvg.ˎ(r0);
        r0 = 0;
        r8.socket = r0;
        r0 = 0;
        r8.rawSocket = r0;
        r0 = 0;
        r8.source = r0;
        r0 = 0;
        r8.sink = r0;
        r0 = 0;
        r8.handshake = r0;
        r0 = 0;
        r8.protocol = r0;
        r0 = 0;
        r8.http2Connection = r0;
        r0 = r8.route;
        r2 = r0.socketAddress();
        r0 = r8.route;
        r3 = r0.proxy();
        r4 = 0;
        r0 = r15;
        r1 = r14;
        r0.connectFailed(r1, r2, r3, r4, r5);
        if (r6 != 0) goto L_0x0121;
    L_0x0113:
        r0 = new okhttp3.internal.connection.RouteException;
        r0.<init>(r5);
    L_0x0118:
        if (r13 == 0) goto L_0x0120;
    L_0x011a:
        r1 = r7.ˎ(r5);
        if (r1 != 0) goto L_0x0126;
    L_0x0120:
        throw r0;
    L_0x0121:
        r6.ॱ(r5);
        r0 = r6;
        goto L_0x0118;
    L_0x0126:
        r6 = r0;
        goto L_0x007a;
    L_0x0129:
        r0 = r8.http2Connection;
        if (r0 == 0) goto L_0x0139;
    L_0x012d:
        r1 = r8.connectionPool;
        monitor-enter(r1);
        r0 = r8.http2Connection;	 Catch:{ all -> 0x013a }
        r0 = r0.ˎ();	 Catch:{ all -> 0x013a }
        r8.allocationLimit = r0;	 Catch:{ all -> 0x013a }
        monitor-exit(r1);	 Catch:{ all -> 0x013a }
    L_0x0139:
        return;
    L_0x013a:
        r0 = move-exception;
        monitor-exit(r1);	 Catch:{ all -> 0x013a }
        throw r0;
    L_0x013d:
        r6 = r0;
        goto L_0x007a;
        */
        throw new UnsupportedOperationException("Method not decompiled: okhttp3.internal.connection.RealConnection.connect(int, int, int, int, boolean, o.ftz, o.fum):void");
    }

    private void connectTunnel(int i, int i2, int i3, ftz o_ftz, fum o_fum) throws IOException {
        fus createTunnelRequest = createTunnelRequest();
        fur ˏ = createTunnelRequest.ˏ();
        int i4 = 0;
        while (i4 < 21) {
            connectSocket(i, i2, o_ftz, o_fum);
            createTunnelRequest = createTunnel(i2, i3, createTunnelRequest, ˏ);
            if (createTunnelRequest != null) {
                fvg.ˎ(this.rawSocket);
                this.rawSocket = null;
                this.sink = null;
                this.source = null;
                o_fum.connectEnd(o_ftz, this.route.socketAddress(), this.route.proxy(), null);
                i4++;
            } else {
                return;
            }
        }
    }

    private void connectSocket(int i, int i2, ftz o_ftz, fum o_fum) throws IOException {
        long j;
        if (this.concurrentConnect == null || this.connectedRoute != null) {
            Socket createSocket;
            Route route = this.connectedRoute != null ? this.connectedRoute : this.route;
            Proxy proxy = route.proxy();
            ftt address = route.address();
            if (proxy.type() == Type.DIRECT || proxy.type() == Type.HTTP) {
                createSocket = address.ˋ().createSocket();
            } else {
                createSocket = new Socket(proxy);
            }
            this.rawSocket = createSocket;
            o_fum.connectStart(o_ftz, this.route.socketAddress(), proxy);
            long currentTimeMillis = System.currentTimeMillis();
            this.rawSocket.setSoTimeout(i2);
            try {
                fwy.ˋ().ˋ(this.rawSocket, route.socketAddress(), i);
                j = currentTimeMillis;
            } catch (Throwable e) {
                ConnectException connectException = new ConnectException("Failed to connect to " + route.socketAddress());
                connectException.initCause(e);
                throw connectException;
            }
        }
        long currentTimeMillis2 = System.currentTimeMillis();
        this.rawSocket = this.concurrentConnect.ˊ((long) i, this.route.proxy(), o_ftz, o_fum);
        if (this.routeSelection != null) {
            this.routeSelection.ॱ(this.concurrentConnect.ˏ());
            if (this.rawSocket != null) {
                this.routeSelection.ॱ((InetSocketAddress) this.rawSocket.getRemoteSocketAddress());
            }
        }
        if (this.rawSocket == null) {
            throw new ConnectException("Failed to connect to host " + this.route.address().ˊ().ʻ());
        }
        this.connectedRoute = new Route(this.route.address(), this.route.proxy(), (InetSocketAddress) this.rawSocket.getRemoteSocketAddress());
        this.route = this.connectedRoute;
        this.rawSocket.setSoTimeout(i2);
        j = currentTimeMillis2;
        this.roughRtt = System.currentTimeMillis() - j;
        this.consecutiveTimeoutThreshold = ((int) ((this.roughRtt * 4) + 1000)) / i2;
        try {
            this.source = fxr.ˎ(fxr.ˎ(this.rawSocket));
            this.sink = fxr.ˋ(fxr.ॱ(this.rawSocket));
        } catch (Throwable e2) {
            if (NPE_THROW_WITH_NULL.equals(e2.getMessage())) {
                throw new IOException(e2);
            }
        }
    }

    private void establishProtocol(fvo o_fvo, int i, ftz o_ftz, fum o_fum) throws IOException {
        if (this.route.address().ॱॱ() != null) {
            o_fum.secureConnectStart(o_ftz);
            connectTls(o_fvo);
            o_fum.secureConnectEnd(o_ftz, this.handshake);
            if (this.protocol == fut.HTTP_2) {
                startHttp2(i);
            }
        } else if (this.route.address().ʻ().contains(fut.H2_PRIOR_KNOWLEDGE)) {
            this.socket = this.rawSocket;
            this.protocol = fut.H2_PRIOR_KNOWLEDGE;
            startHttp2(i);
        } else {
            this.socket = this.rawSocket;
            this.protocol = fut.HTTP_1_1;
        }
    }

    private void startHttp2(int i) throws IOException {
        this.socket.setSoTimeout(0);
        this.http2Connection = new fwk.b(true).ˊ(this.socket, this.route.address().ˊ().ʻ(), this.source, this.sink).ˊ(this).ॱ(i).ॱ();
        this.http2Connection.ˊ();
    }

    private void connectTls(fvo o_fvo) throws IOException {
        Throwable th;
        Socket socket;
        AssertionError assertionError;
        Throwable th2;
        String str = null;
        ftt address = this.route.address();
        try {
            SSLSocket sSLSocket = (SSLSocket) address.ॱॱ().createSocket(this.rawSocket, address.ˊ().ʻ(), address.ˊ().ॱॱ(), true);
            try {
                String ˏ = address.ˏ();
                if (ˏ == null || ˏ.length() == 0) {
                    ˏ = address.ˊ().ʻ();
                }
                fud ˊ = o_fvo.ˊ(sSLSocket);
                if (ˊ.ॱ()) {
                    fwy.ˋ().ॱ(sSLSocket, ˏ, address.ʻ());
                }
                sSLSocket.startHandshake();
                SSLSession session = sSLSocket.getSession();
                fuk ॱ = fuk.ॱ(session);
                if (address.ͺ().verify(ˏ, session)) {
                    fut ˊ2;
                    address.ˋॱ().ˊ(address.ˊ().ʻ(), ॱ.ˎ());
                    if (ˊ.ॱ()) {
                        str = fwy.ˋ().ˊ(sSLSocket);
                    }
                    this.socket = sSLSocket;
                    this.source = fxr.ˎ(fxr.ˎ(this.socket));
                    this.sink = fxr.ˋ(fxr.ॱ(this.socket));
                    this.handshake = ॱ;
                    if (str != null) {
                        ˊ2 = fut.ˊ(str);
                    } else {
                        ˊ2 = fut.HTTP_1_1;
                    }
                    this.protocol = ˊ2;
                    if (sSLSocket != null) {
                        fwy.ˋ().ˏ(sSLSocket);
                        return;
                    }
                    return;
                }
                List ˎ = ॱ.ˎ();
                if (ˎ.isEmpty()) {
                    throw new SSLPeerUnverifiedException("Hostname " + address.ˊ().ʻ() + " not verified (no certificates)");
                }
                Certificate certificate = (X509Certificate) ˎ.get(0);
                throw new SSLPeerUnverifiedException("Hostname " + address.ˊ().ʻ() + " not verified:\n    certificate: " + fty.ˏ(certificate) + "\n    DN: " + certificate.getSubjectDN().getName() + "\n    subjectAltNames: " + fxc.ˏ(certificate));
            } catch (Throwable e) {
                th = e;
                socket = sSLSocket;
                assertionError = th;
                try {
                    if (fvg.ˎ(assertionError)) {
                        throw assertionError;
                    } else {
                        throw new IOException(assertionError);
                    }
                } catch (Throwable th3) {
                    th2 = th3;
                }
            } catch (Throwable e2) {
                th = e2;
                socket = sSLSocket;
                th2 = th;
                if (socket != null) {
                    fwy.ˋ().ˏ((SSLSocket) socket);
                }
                fvg.ˎ(socket);
                throw th2;
            }
        } catch (AssertionError e3) {
            assertionError = e3;
            if (fvg.ˎ(assertionError)) {
                throw assertionError;
            } else {
                throw new IOException(assertionError);
            }
        }
    }

    private fus createTunnel(int i, int i2, fus o_fus, fur o_fur) throws IOException {
        String str = "CONNECT " + fvg.ॱ(o_fur, true) + " HTTP/1.1";
        fvb ˏ;
        do {
            fwe o_fwe = new fwe(null, null, this.source, this.sink);
            this.source.ˊ().ˊ((long) i, TimeUnit.MILLISECONDS);
            this.sink.ˊ().ˊ((long) i2, TimeUnit.MILLISECONDS);
            o_fwe.ˏ(o_fus.ॱ(), str);
            o_fwe.ॱ();
            ˏ = o_fwe.ˏ(false).ˎ(o_fus).ˏ();
            long ˏ2 = fvr.ˏ(ˏ);
            if (ˏ2 == -1) {
                ˏ2 = 0;
            }
            fxw ˏ3 = o_fwe.ˏ(ˏ2);
            try {
                fvg.ˎ(ˏ3, (int) ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED, TimeUnit.MILLISECONDS);
                ˏ3.close();
                switch (ˏ.ˊ()) {
                    case 200:
                        if (this.source.ˏ().ᐝ() && this.sink.ˏ().ᐝ()) {
                            return null;
                        }
                        throw new IOException("TLS tunnel buffered too many bytes!");
                    case 407:
                        o_fus = this.route.address().ॱ().ॱ(this.route, ˏ);
                        if (o_fus != null) {
                            break;
                        }
                        throw new IOException("Failed to authenticate with proxy");
                    default:
                        throw new IOException("Unexpected response code for CONNECT: " + ˏ.ˊ());
                }
            } catch (IOException e) {
                throw e;
            } catch (Throwable th) {
                ˏ3.close();
            }
        } while (!"close".equalsIgnoreCase(ˏ.ˋ("Connection")));
        return o_fus;
    }

    private fus createTunnelRequest() throws IOException {
        fus ॱ = new fus.a().ˊ(this.route.address().ˊ()).ˎ("CONNECT", null).ॱ("Host", fvg.ॱ(this.route.address().ˊ(), true)).ॱ("Proxy-Connection", "Keep-Alive").ॱ("User-Agent", fvc.ˋ()).ॱ();
        fus ॱ2 = this.route.address().ॱ().ॱ(this.route, new d().ˎ(ॱ).ॱ(fut.HTTP_1_1).ॱ(407).ˊ("Preemptive Authenticate").ॱ(fvg.ॱ).ॱ(-1).ˏ(-1).ˊ("Proxy-Authenticate", "OkHttp-Preemptive").ˏ());
        return ॱ2 != null ? ॱ2 : ॱ;
    }

    public boolean isEligible(ftt o_ftt, @Nullable Route route) {
        if (this.allocations.size() >= this.allocationLimit || this.noNewStreams || !fux.ˏ.ˊ(this.route.address(), o_ftt)) {
            return false;
        }
        if (o_ftt.ˊ().ʻ().equals(route().address().ˊ().ʻ())) {
            return true;
        }
        if (this.http2Connection == null || route == null || route.proxy().type() != Type.DIRECT || this.route.proxy().type() != Type.DIRECT || !this.route.socketAddress().equals(route.socketAddress()) || route.address().ͺ() != fxc.ˊ || !supportsUrl(o_ftt.ˊ())) {
            return false;
        }
        try {
            o_ftt.ˋॱ().ˊ(o_ftt.ˊ().ʻ(), handshake().ˎ());
            return true;
        } catch (SSLPeerUnverifiedException e) {
            return false;
        }
    }

    public boolean supportsUrl(fur o_fur) {
        if (o_fur.ॱॱ() != this.route.address().ˊ().ॱॱ()) {
            return false;
        }
        if (o_fur.ʻ().equals(this.route.address().ˊ().ʻ())) {
            return true;
        }
        boolean z = this.handshake != null && fxc.ˊ.ॱ(o_fur.ʻ(), (X509Certificate) this.handshake.ˎ().get(0));
        return z;
    }

    public fvv newCodec(fuv o_fuv, fuo.d dVar, StreamAllocation streamAllocation) throws SocketException {
        if (this.http2Connection != null) {
            return new fwj(o_fuv, dVar, streamAllocation, this.http2Connection);
        }
        this.socket.setSoTimeout(dVar.ˋ());
        this.source.ˊ().ˊ((long) dVar.ˋ(), TimeUnit.MILLISECONDS);
        this.sink.ˊ().ˊ((long) dVar.ˎ(), TimeUnit.MILLISECONDS);
        return new fwe(o_fuv, streamAllocation, this.source, this.sink);
    }

    public e newWebSocketStreams(StreamAllocation streamAllocation) {
        final StreamAllocation streamAllocation2 = streamAllocation;
        return new e(this, true, this.source, this.sink) {
            final /* synthetic */ RealConnection ॱ;

            public void close() throws IOException {
                streamAllocation2.streamFinished(true, streamAllocation2.codec(), -1, null);
            }
        };
    }

    public Route route() {
        return this.route;
    }

    public void cancel() {
        if (this.concurrentConnect != null) {
            this.concurrentConnect.ˊ();
        }
        fvg.ˎ(this.rawSocket);
    }

    public Socket socket() {
        return this.socket;
    }

    public boolean isHealthy(boolean z) {
        if (this.socket.isClosed() || this.socket.isInputShutdown() || this.socket.isOutputShutdown()) {
            return false;
        }
        if (this.http2Connection != null) {
            if (this.http2Connection.ˏ()) {
                return false;
            }
            return true;
        } else if (!z) {
            return true;
        } else {
            int soTimeout;
            try {
                soTimeout = this.socket.getSoTimeout();
                this.socket.setSoTimeout(1);
                if (this.source.ᐝ()) {
                    this.socket.setSoTimeout(soTimeout);
                    return false;
                }
                this.socket.setSoTimeout(soTimeout);
                return true;
            } catch (SocketTimeoutException e) {
                return true;
            } catch (IOException e2) {
                return false;
            } catch (Throwable th) {
                this.socket.setSoTimeout(soTimeout);
            }
        }
    }

    public void onStream(fwh o_fwh) throws IOException {
        o_fwh.ˎ(fwf.REFUSED_STREAM);
    }

    public void onSettings(fwk o_fwk) {
        synchronized (this.connectionPool) {
            this.allocationLimit = o_fwk.ˎ();
        }
    }

    public fuk handshake() {
        return this.handshake;
    }

    public boolean isMultiplexed() {
        return this.http2Connection != null;
    }

    public fut protocol() {
        return this.protocol;
    }

    public String toString() {
        Object ॱ;
        StringBuilder append = new StringBuilder().append("Connection{").append(this.route.address().ˊ().ʻ()).append(":").append(this.route.address().ˊ().ॱॱ()).append(", proxy=").append(this.route.proxy()).append(" hostAddress=").append(this.route.socketAddress()).append(" cipherSuite=");
        if (this.handshake != null) {
            ॱ = this.handshake.ॱ();
        } else {
            ॱ = com.huawei.hwCloudJs.d.d.a;
        }
        return append.append(ॱ).append(" protocol=").append(this.protocol).append('}').toString();
    }
}
